#import <UIKit/UIKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "social.h"
#import "facebook.h"

@implementation FacebookPlatformProvider
{
    SocialRequestCompletionHandler authHandler;
    SocialRequestCompletionHandler shareHandler;
}
-(id)init
{
    return [super init];
}
-(void)launch:(NSDictionary *)launchOptions{
    [[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
                             didFinishLaunchingWithOptions:launchOptions];
}
-(void)setAppKey:(NSString *)appKey
   withAppSecret:(NSString *)appSecret
 withRedirectURL:(NSString *)redirectURL{
    self->_appKey = appKey;
    self->_appSecret = appSecret;
}
-(void)AuthorizeWithUserInfo:(NSDictionary *)userInfo
       withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    SocialUserInfoResponse *response = [[SocialUserInfoResponse alloc] init];
    self->authHandler = completionHandler;
    if ([FBSDKAccessToken currentAccessToken]) {
        // User is logged in, do work such as go to next view controller.

        response.accessToken = [[FBSDKAccessToken currentAccessToken] tokenString];
        response.openId = [[FBSDKAccessToken currentAccessToken] userID];
        response.expiration = [[FBSDKAccessToken currentAccessToken] expirationDate];
        [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name"}] startWithCompletion:^(id<FBSDKGraphRequestConnecting>  _Nullable connection, id  _Nullable result, NSError * _Nullable error) {
            if (!error) {
                response.nickName = [result objectForKey:@"name"];
                response.gender = [result objectForKey:@"gender"];
            }
            NSError *err;
            if (error) {
                err = [NSError errorWithDomain:@"facebook auth" code:10 userInfo:nil];
            }
            self->authHandler(response,err);
        }];
        return;
    }
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login
     logInWithPermissions: @[@"public_profile"]
     fromViewController:nil
     handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
         NSError *err;
         if (error) {
             err = [NSError errorWithDomain:@"facebook auth" code:10 userInfo:nil];
             self->authHandler(response,err);
         } else if (result.isCancelled) {
             err = [NSError errorWithDomain:@"facebook auth" code:11 userInfo:nil];
             self->authHandler(response,err);
         } else {
             response.accessToken = [[FBSDKAccessToken currentAccessToken] tokenString];
             response.openId = [[FBSDKAccessToken currentAccessToken] userID];
             response.expiration = [[FBSDKAccessToken currentAccessToken] expirationDate];
             [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name"}] startWithCompletion:^(id<FBSDKGraphRequestConnecting>  _Nullable connection, id  _Nullable result, NSError * _Nullable error) {
                 if (!error) {
                     response.nickName = [result objectForKey:@"name"];
                     response.gender = [result objectForKey:@"gender"];
                 }
                 self->authHandler(response,err);
             }];
             
         }
     }];
}

-(void)AuthorizedWithUserInfo:(NSDictionary *)userInfo
        withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    SocialAuthResponse *response = [SocialAuthResponse init];
    NSError *err = [NSError errorWithDomain:@"facebook auth" code:10 userInfo:nil];
    completionHandler(response,err);
}

-(void)ShareWithObject:(SocialMessageObject *)object
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    
}
-(void)LeaderboardWith:(NSString *)key withValue:(int) value
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    NSError *err = [NSError errorWithDomain:@"facebook leaderboard" code:10 userInfo:nil];
    completionHandler(nil,err);
}
-(void)AchievementWith:(NSString *)key withValue:(int) value
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    NSError *err = [NSError errorWithDomain:@"facebook achievement" code:10 userInfo:nil];
    completionHandler(nil,err);
}

/**
 *  获得从sso或者web端回调到本app的回调
 *
 *  @param url 第三方sdk的打开本app的回调的url
 *
 *  @return 是否处理  YES代表处理成功，NO代表不处理
 */
-(BOOL)handleOpenURL:(NSURL *)url{
    return false;
}
-(BOOL)handleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
                                                                  openURL:url
                                                        sourceApplication:sourceApplication
                                                               annotation:annotation
                    ];
    // Add any custom logic here.
    return handled;
}
-(BOOL)handleOpenURL:(NSURL *)url options:(NSDictionary*)options{
    BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
                                                                  openURL:url
                                                        sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                                               annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
                    ];
    // Add any custom logic here.
    return handled;
}

-(BOOL)isInstall{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]];
}
-(BOOL)isSupport{
    return [self isInstall];
}

-(BOOL)isLeaderboard{
    return false;
}
-(BOOL)isAchievement{
    return false;
}
@end
